<?php
/**
 * Created by PhpStorm.
 * User: chenguangpeng
 * Date: 15-8-14
 * Time: 下午6:29
 */

namespace Api;
/**
 *携程对接
 *2015-04-30
 *by pzp
 *TicketSenicSpotInfo->[ScenicSpotList]->[ID] 是景区ID
 *TicketSenicSpotInfo->[ScenicSpotList]->[ProductList]->[ProductBasicInfo]->[ID] 是产品ID
 *TicketSenicSpotInfo->[ScenicSpotList]->[ProductList]->[ResourceList]->[ID] 是资源ID
 **/
class Ctrip{

    private $post_array = array(
        'AllianceID'    => 22666, //联盟id
        'SID'           => 456827, //站点id
        'APIKey'        => '899480A9-2747-4F61-A0F2-17302A82B187',// 密钥
        'reqUri'        => 'http://openapi.ctrip.com/vacations/OpenServer.ashx',
        'ProtocolType'  => 1, //0是xml，1是json
    );

    //3.1查询门票景点列表
    public function TicketSenicSpotSearch($Keyword, $page=1, $size=10){
        $this->post_array['RequestType']="TicketSenicSpotSearch";
        $reqJson=<<<H
{
    "DistributionChannel": 9,
    "PagingParameter": {
        "PageIndex": $page,
        "PageSize": $size
    },
    "SearchParameter": {
        "Keyword": "$Keyword",
        "SaleCityID": 2,
    }
}
H;
        $time = time();
        $this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
        $this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
        $Ctrip_RequestData = $this->Ctrip_RequestData($time,$this->post_array);
        foreach($Ctrip_RequestData['ScenicSpotListItemList'] as $productid){
            $productids['id'] = $productid['ID'];
            $productids['Name'] = $productid['Name'];
            $productidss['list'][] = $productids;
        }
        $productidss['count'] = $Ctrip_RequestData['LabelSatistics'][0]['SubLabelSatistics'][0]['Count'];
        return $productidss;
    }

    //请求接口服务的名称:门票景点详情
    public function TicketSenicSpotInfo($productid){
        $this->post_array['RequestType']="TicketSenicSpotInfo";
        $reqJson=<<<H
{
    "DistributionChannel": 9,
    "ResponseDataType": 0,
    "ID": [
      $productid
    ],
    "ProductId": null,
    "DebugKey": null,
    "ImageSize": null
}
H;
        $time = time();
        $this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
        $this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
        $Ctrip_RequestData = $this->Ctrip_RequestData($time,$this->post_array);
//         return $Ctrip_RequestData ;
        $data = array();
        foreach($Ctrip_RequestData['ScenicSpotList'] as $s){
            $data[$s['ID']]['land'] = array(
                'product_type'  => 'A',
                'product_name'  => $s['Name'],
                'city'          => $s['ProvinceName'] .'|'. $s['DistrictName'],
                'address'       => $s['Address'],
                'product_level' => $s['Star'],
                'tel'           => '',
                'fax'           => '',
                'opentime'      => '',
                'runtime'       => $s['OpenTimeDesc'],
                'imgpath'       => $s['Image'],
                'lat'           => $s['Latitude'],
                'lng'           => $s['Longitude'],
            );

            foreach($s['ProductList'] as $Ps){
                if($Ps){
                    //详情
                    $data[$s['ID']]['land']['product_id'] = $Ps['ProductBasicInfo']['ID'];
                    $data[$s['ID']]['land']['detail'] = $Ps['ProductDescriptionInfo']['Introduction'];
                    $C_Pins= array();
                    foreach($Ps['ProductAddInfoList'] as $Pin){
                        $deac = '';
                        foreach($Pin['ProductAddInfoDetailList'] as $Pin2){
                            $deac.= $Pin2['DescDetail'];
                        }
                        $C_Pins[]=$Pin['AddInfoSubTitleName'].":".$deac;
                    }
                    $data[$s['ID']]['land']['notice'] = implode("\n", $C_Pins);
                    foreach($Ps['ResourceList'] as $R){
                        $RADDdata1 = '';
                        foreach($R['ResourceAddInfoList'] as $RADDdata){
                            $RADDdata1.=$RADDdata['Description'];
                        }
                        $data[$s['ID']]['tickets'][] = array(
                            'id'                =>$R['ID'],
                            'ticket_name'       =>$R['Name'],
                            'get_ticket_info'   =>$RADDdata1,
                            'notes'             =>$R['Description'],
                            'payment_type'      => $R['PayMode']=='P' ? 1 : 0,
                            'total_storage'     =>-1,
                            'auto_cancel_minute'=>120,
                            'use_delay_type'    =>0,//当天有效
                            'use_delay_days'    =>30,//当天有效
                            'book_early_days'   =>$R['AdvanceBookingDays'],//资源提前预定天数
                            'book_deadline'     =>$R['AdvanceBookingTime'],//提前预订截止时间
                            'refundcharge'      =>0,//退票手续费
                            'idcard_verify'     =>$R['RealNameType'],
                            'buy_min_num'       =>$R['MinQuantity'],
                            'buy_max_num'       =>$R['MaxQuantity'],
                            'verify_start_time' =>'',
                            'market_price'      =>$R['MarketPrice'],
                            'update_time'       => date('Y-m-d H:i:s'),
                            'Mpath'             =>'http://10.160.4.140/new/d/module/api/ctrip/ctrip_get_data.php',//携程的都是这个
                            'sourceT'           =>2,//同上
                            'price_array'       => array(
                                'start_date'        => date('Y-m-d', $_SERVER['REQUEST_TIME']),
                                'end_date'          => date('Y-12-31', $_SERVER['REQUEST_TIME']),
                                'valid_week'        => '0,1,2,3,4,5,6',
                                'storage'           => -1,
                                'supply_price'      =>$R['Price'] * 100,
                                'retail_price'      =>$R['MarketPrice'] * 100,
                                'ptype'             =>0,
                            ),
                        );
                    }
                }
            }
        }
        return($data);
    }

    //根据景区ID获取数据 只返回ID和名称 没有上面一个方法的数据那么详细
    public function TicketSenicSpotInfo_simple($productid){
        $this->post_array['RequestType']="TicketSenicSpotInfo";
        $reqJson=<<<H
{
    "DistributionChannel": 9,
    "ResponseDataType": 0,
    "ID": [
      $productid
    ],
    "ProductId": null,
    "DebugKey": null,
    "ImageSize": null
}
H;
        $time = time();
        $this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
        $this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
        $Ctrip_RequestData = $this->Ctrip_RequestData($time,$this->post_array);
        foreach($Ctrip_RequestData['ScenicSpotList'] as $productid){
            $productidss['list'][] = array(
                'id'	=> $productid['ID'],
                'Name'	=> $productid['Name']
            );
        }
        $productidss['count'] = 1;
        return $productidss;
    }
    //3.3门票资源价格库查询
    public function TicketResourcePriceAndInventory($ProductID, $ResourceID){
        $this->post_array['RequestType']="TicketResourcePriceAndInventory";
        $reqJson=<<<H
{
    "DistributionChannel": 9,
    "ProductID": $ProductID,
    "ResourcePriceAndInventoryRequestItemList": [
        {
            "EndDate": "2015-12-31T11:27:25",
            "ResourceID": $ResourceID,
            "StartDate": "2012-7-17T11:27:25"
        }
    ]
}
H;
        $time = time();
        $this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
        $this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
        $Ctrip_RequestData = $this->Ctrip_RequestData($time,$this->post_array);
        return $Ctrip_RequestData;

    }

    //3.4门票可订性检查
    public function TicketOrderCanBooking(){
        $this->post_array['RequestType'] = 'TicketOrderCanBooking';
        $reqJson=<<<H
{
    "DistributionChannel": 9,
    "OrderTotalPrice": 120,
    "PromotionList": null,
    "ResourceCanBookingRequestItemList": [
        {
            "ResourceID": 269031,
            "TotalPrice": 120,
            "UseDate": "2015-05-15T22:18:05+08:00",
            "UseQuantity": 1
        }
    ]
}
H;
        $time = time();
        $this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
        $this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
        $Ctrip_RequestData = $this->Ctrip_RequestData($time,$this->post_array);
        return $Ctrip_RequestData;

    }

    //创建订单
    public function TicketOrderCreateForPrepay_V2($request_array){
        // print_r($request_array);exit;
        $this->post_array['RequestType'] = 'TicketOrderCreateForPrepay_V2';
        $Amount = $request_array['UUtnum']*$request_array['UUlprice'];
        $reqJson=<<<H
{
    "AdultNumber": "{$request_array['UUtnum']}",
    "Amount": "$Amount",
    "ClientInfoList": [
        {
            "AgeType": "ADU",
            "BirthCity": null,
            "BirthDate": "1990-05-01T00:00:00",
            "CardCity": null,
            "ClientName": "{$request_array['pftordername']}",
            "ClientName_E": "test/test",
            "ContactInfo": "{$request_array['UUordertel']}",
            "Gender": 0,
            "HzAdd": null,
            "HzDate": "0001-01-01T00:00:00",
            "HzNo": "0",
            "IDCardNo": "{$request_array['IDcar']}",
            "IDCardTimelimit": "0001-01-01T00:00:00",
            "IDCardType": 1,
            "InfoID": 0,
            "IssueDate": "0001-01-01T00:00:00",
            "Nationality": null,
            "PassportType": "P",
            "VisaCountry": null
        }
    ],
    "DistributorOrderID": "{$request_array['pftordernum']}",
    "ContactInfo": {
        "ContactAddress": null,
        "ContactEmail": "test@test.com",
        "ContactFax": null,
        "ContactMobile": "{$request_array['UUordertel']}",
        "ContactName": "{$request_array['pftordername']}",
        "ContactTel": null
    },
    "ProductInfo": {
        "ProductID": "{$request_array['ProductID']}",
    },
    "Remark": "特殊说明",
    "SalesCity": 2,
    "TicketInfo": [
        {
            "Price": "{$Amount}",
            "TicketID": "{$request_array['TicketID']}",
            "UseDate": "{$request_array['UUplaytime']}T23:59:59",
            "Quantity": "{$request_array['UUtnum']}",
            "TicketType": 0
        }
    ],
"Uid": "{$request_array['Uid']}"
}
H;
        // print_r($reqJson);
        $time = time();
        $this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
        $this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
        $Ctrip_RequestData = $this->Ctrip_RequestData2($time,$this->post_array);
        if($Ctrip_RequestData['IsSucceed'] == 'true'){
            return 100;
        }
        else{
            // $this->logfile($reqJson);
            $error_msg = $Ctrip_RequestData;
            $error_log = $this->logfile(date('Y-m-d H:i:s').'---'.$error_msg,'/var/www/html/new/d/module/api/ctrip/ctrip_logfile.txt');
            return 101;
        }
    }

    //查询订单
    public function SeachOrder($searchTime){
        $OrderStartUseDate = date('Y-m-d\TH:i:s', $_SERVER['REQUEST_TIME']);
        $timer=strtotime($OrderStartUseDate)+10*60;
        $OrderEndUseDate = date('Y-m-d\TH:i:s',$timer);

        // $OrderStartUseDate = $searchTime."T00:00:00";
        // $OrderEndUseDate = $searchTime."T23:59:59";
        $this->post_array['RequestType'] = 'TicketSearchOrder';
        $reqJson = <<<H
{
    "OrderSearchParameter": {
        "AllianceId": {$this->post_array['AllianceID']},
        "ClientName": "",
        "OrderEndDate": "",
        "OrderEndUseDate": "{$OrderEndUseDate}",
        "OrderId": 0,
        "OrderStartDate": "",
        "OrderStartUseDate": "{$OrderStartUseDate}",
        "OrderStatus": null,
        "OUID": "",
        "SID": {$this->post_array['SID']},
        "Uid": ""
    },
    "PagingParameter": {
        "PageIndex": 1,
        "PageSize": 10000
    },
    "SortParameter": {
        "SortDirection": "desc",
        "SortKey": "",
        "SortType": "2"
    }
}
H;
        $time = time();
        $this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
        $this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
        $Ctrip_RequestData = $this->Ctrip_RequestData2($time,$this->post_array);
        return $Ctrip_RequestData;
    }
    //退单
    public function TicketUnsubscribeOrder($ctrip_OrderId){
        $this->post_array['RequestType'] = 'TicketUnsubscribeOrder';
        $reqJson=<<<H
{
    "DistributionChannelId": 9,
    "OrderId": "{$ctrip_OrderId}",
    "Reason": "",
    "Remark": ""
}
H;
        $time = time();
        $this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
        $this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
        $Ctrip_RequestData = $this->Ctrip_RequestData2($time,$this->post_array);
        // $error_log = $this->logfile(date('Y-m-d H:i:s').'---'.json_encode($Ctrip_RequestData));
        // $this->logfile($Ctrip_RequestData);return 101;
        if($Ctrip_RequestData['IsSucceed'] == 'true'){
            return 100;
        }
        else{
            $error_log = $this->logfile(date('Y-m-d H:i:s').'---'.$ctrip_OrderId.'->'.$Ctrip_RequestData,'/var/www/html/new/d/module/api/ctrip/ctrip_logfile.txt');
            return 101;
        }
    }


    /*以下是共用函数部分*/
    public function sign($time,$RequestType){
        $t = $time.$this->post_array['AllianceID'].strtoupper(md5($this->post_array['APIKey'])).$this->post_array['SID'].$RequestType;
        $signature = strtoupper(md5($t));
        return $signature;
    }

    public function Ctrip_RequestData($time,$array){
        $post_array = $this->zh_bm($array);
        $post_array =<<<h
{
	"AllianceID":"{$post_array['AllianceID']}",
	"SID":"{$post_array['SID']}",
	"ProtocolType":"{$post_array['ProtocolType']}",
	"Signature":"{$post_array['signature']}",
	"TimeStamp":"$time",
	"Channel":"Vacations",
	"Interface":"{$post_array['RequestType']}",
	"IsError":false,
	"RequestBody":"{$post_array['reqJson']}",
	"ResponseBody":"",
	"ErrorMessage":""
}
h;
        $tmp = array();
        $tmp['RequestJson'] = urlencode($post_array);
        $data = "RequestJson=".$tmp['RequestJson'];

        $ch = curl_init();//打开
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $this->post_array['reqUri']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $response  = curl_exec($ch);
        curl_close($ch);//关闭
        $date_response_ResponseBody = json_decode($response,true);
        if($date_response_ResponseBody['ResponseBody']){
            $product_data = json_decode($date_response_ResponseBody['ResponseBody'],true);
            return $product_data;
        }
        else{
            return $date_response_ResponseBody['ErrorMessage'];
        }
    }

    public function Ctrip_RequestData2($time,$array){
        $post_array = $this->zh_bm($array);
        $post_array =<<<h
{
	"AllianceID":"{$post_array['AllianceID']}",
	"SID":"{$post_array['SID']}",
	"ProtocolType":"{$post_array['ProtocolType']}",
	"Signature":"{$post_array['signature']}",
	"TimeStamp":"$time",
	"Channel":"Vacations",
	"Interface":"{$post_array['RequestType']}",
	"IsError":false,
	"RequestBody":"{$post_array['reqJson']}",
	"ResponseBody":"",
	"ErrorMessage":""
}
h;
        $tmp = array();
        $tmp['RequestJson'] = urlencode($post_array);
        $data = "RequestJson=".$tmp['RequestJson'];

        $ch = curl_init();//打开
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $this->post_array['reqUri']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $response  = curl_exec($ch);
        curl_close($ch);//关闭
        $date_response_ResponseBody = json_decode($response,true);
        // print_r($post_array);exit;
        // return $date_response_ResponseBody;
        if($date_response_ResponseBody['ResponseBody']){
            $product_data = json_decode($date_response_ResponseBody['ResponseBody'],true);
            return $product_data;
        }
        else{
            return $date_response_ResponseBody['ErrorMessage'];
        }
    }

    public function zh_bm($arr){  //转换编码
        if(is_array($arr)){
            foreach($arr as $k => $v){
                $arr[$k] = $this->zh_bm($v);
            }
            return $arr;
        }
        return iconv("UTF-8","GB2312//IGNORE",$arr);
    }

    //日志
    public function logfile($txt,$path){
        $fp = fopen($path,"a");
        flock($fp, LOCK_EX) ;
        fwrite($fp,$txt."\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }

    public static function raw_post($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        return curl_exec($ch);
    }
}
?>